package com.cskaoyan.mall.controller;

import com.cskaoyan.mall.model.Goods;
import com.cskaoyan.mall.model.Result;
import com.cskaoyan.mall.model.Type;
import com.cskaoyan.mall.model.bo.*;
import com.cskaoyan.mall.model.vo.GetSpecsVO;
import com.cskaoyan.mall.model.vo.GoodsInfoVO;
import com.cskaoyan.mall.model.vo.MsgReplyVO;
import com.cskaoyan.mall.model.vo.MsgVO;
import com.cskaoyan.mall.service.GoodsService;
import com.cskaoyan.mall.service.GoodsServiceImpl;
import com.cskaoyan.mall.utils.FileUploadUtils;
import com.cskaoyan.mall.utils.HttpUtils;
import com.cskaoyan.mall.utils.StringUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {
    private Gson gson = new Gson();
    private GoodsService goodsService = new GoodsServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/","");
        if ("imgUpload".equals(action)) {
            imgUpload(request,response);
        }else if ("addGoods".equals(action)) {
            addGoods(request,response);
        }else if ("addType".equals(action)) {
            addType(request,response);
        }else if ("addSpec".equals(action)) {
            addSpec(request,response);
        }else if ("updateGoods".equals(action)) {
            updateGoods(request,response);
        }else if ("deleteSpec".equals(action)) {
            deleteSpec(request,response);
        }else if ("reply".equals(action)) {
            reply(request,response);
        }
    }

    /**
     * 回复留言内容
     * @param request
     * @param response
     */
    private void reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        ReplyBO replyBO = gson.fromJson(requestBody,ReplyBO.class);
        int code = goodsService.reply(replyBO);
        if (code == 200) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("回复失败！")));
    }

    /**
     * 在修改商品详情的时候，删除某个规格详情
     * {goodsId: "5", specName: "数学二"}
     * @param request
     * @param response
     */
    private void deleteSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        DeleteSpecBO deleteSpecBO = gson.fromJson(requestBody,DeleteSpecBO.class);
        int code = goodsService.deleteSpec(deleteSpecBO);
        if (code == 200) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除规格失败")));
    }
    /*
        desc: "可爱，小萌妹必备"
        id: "3"
        name: "2020可爱背包"
        specList: [{id: 5, specName: "小号", stockNum: 200, unitPrice: 50},…]
        0: {id: 5, specName: "小号", stockNum: 200, unitPrice: 50}
        1: {id: 6, specName: "大号", stockNum: 150, unitPrice: 55}
        2: {goodsId: "3", specName: "XXXL码", stockNum: "1", unitPrice: "1"}
        typeId: 2
         */

    /**
     * 更新商品详情
     * @param request
     * @param response
     */
    private void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        //从请求体中获取规格的具体信息
        UpdateGoodsBO updateGoodsBO = gson.fromJson(requestBody,UpdateGoodsBO.class);
        int code = goodsService.updateGoods(updateGoodsBO);
        if (code == 200) {
            response.getWriter().println(gson.toJson(Result.ok("修改成功")));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("修改失败")));
    }

    /**
     * 添加商品的规格
     * {"code":0,"data":{"goodsId":"476","specName":"所示","stockNum":"11","unitPrice":"11"}}
     * {"code":0,"data":{"goodsId":"2","specName":"S码","stockNum":"20","unitPrice":"20"}}
     * @param request
     * @param response
     */
    private void addSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        //从请求体中获取规格的具体信息
        AddSpecsBO addSpecsBO = gson.fromJson(requestBody,AddSpecsBO.class);
        System.out.println(addSpecsBO);
        if (!StringUtils.isNumeric(addSpecsBO.getStockNum()) || !StringUtils.isNumeric(addSpecsBO.getUnitPrice()) || !StringUtils.isNumeric(addSpecsBO.getGoodsId())) {
            response.getWriter().println(gson.toJson(Result.error("请输入正确的规格参数")));
            System.out.println("请输入正确的参数");
            return;
        }
        int code = goodsService.addSpec(addSpecsBO);
        if (code == 200) {
//            GetSpecsVO getSpecsVO = new GetSpecsVO(Integer.parseInt(addSpecsBO.getGoodsId()), addSpecsBO.getSpecName(), Integer.parseInt(addSpecsBO.getStockNum()), Double.parseDouble(addSpecsBO.getUnitPrice()));
            System.out.println(addSpecsBO);
            response.getWriter().println(gson.toJson(Result.ok(addSpecsBO)));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("插入操作失败")));
    }

    /**
     * 获取全部的商品类型
     * @param request
     * @param response
     * @throws IOException
     */
    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> typeList = goodsService.getType();
        response.getWriter().println(gson.toJson(Result.ok(typeList)));
    }
    /**
     * 添加商品，包括商品名称，类目，图片，规格（名称，库存，价格），详情描述
     * @param request
     * @param response
     */
    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        //从请求体中获取商品的具体信息
        AddGoodsBO addGoodsBO = gson.fromJson(requestBody,AddGoodsBO.class);
        System.out.println(addGoodsBO);
        //校验库存，数字 价格 数字
        List<AddSpecBO> specList = addGoodsBO.getSpecList();
        for (AddSpecBO addSpecBO : specList) {
            if (!StringUtils.isNumeric(addSpecBO.getStockNum()) || !StringUtils.isNumeric(addSpecBO.getUnitPrice())) {
                response.getWriter().println(gson.toJson(Result.error("请输入正确的规格参数")));
                System.out.println("请输入争取的参数");
                return;
            }
        }
        goodsService.addGoods(addGoodsBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 添加商品时的图片上传
     * @param request
     * @param response
     */
    private void imgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*
        1、属性值 value就是文件保存的路径
        文件的路径地址不是以域名端口号开始的，那么会补上前端的域名和端口号
        需要注意一点：图片是上传到8084服务器系统内部的，所有的路径必须是有域名端口号完整的路径
         */
        Map<String,Object> map = FileUploadUtils.parseRequest(request);
        System.out.println("map: " + map);
        String file = (String) map.get("file");
        //拼接出当前的域名和端口号
        String domain = (String) getServletContext().getAttribute("domain");
        response.getWriter().println(gson.toJson(Result.ok(domain + "/" + file)));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/","");
        if ("getType".equals(action)) {
            getType(request,response);
        }else if ("getGoodsByType".equals(action)) {
            getGoodsByType(request,response);
        }else if ("deleteType".equals(action)) {
            deleteType(request,response);
        }else if ("getGoodsInfo".equals(action)) {
            getGoodsInfo(request,response);
        }else if ("deleteGoods".equals(action)) {
            deleteGoods(request,response);
        }else if ("noReplyMsg".equals(action)) {
            noReplyMsg(request,response);
        }else if ("repliedMsg".equals(action)) {
            repliedMsg(request,response);
        }

    }

    /**
     * 已经处理的消息列表，比未处理的多了一个replyContent
     * @param request
     * @param response
     */
    private void repliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<MsgReplyVO> msgs = goodsService.repliedMsg();
        response.getWriter().println(gson.toJson(Result.ok(msgs)));
    }

    /**
     * 返回未处理的消息列表
     * {"code":0,
     * "data":
     * [{"id":357,
     * "userId":503,
     * "goodsId":610,
     * "content":"kanyixia",
     * "state":1,
     * "createtime":"2020-08-10 22:58:39",
     * "goods":{"name":"xiaomi"},
     * "user":{"name":"debug"}},
     * @param response
     */
    private void noReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<MsgVO> msgs = goodsService.noReplyMsg();
        response.getWriter().println(gson.toJson(Result.ok(msgs)));
    }

    private void deleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int code = goodsService.deleteGoods(id);
        if (code == 200) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除失败")));
    }

     /*{"code":0,
        "data":{
        "specs":[{"id":1233,"specName":"l","stockNum":83,"unitPrice":500.0},
            {"id":1829,"specName":"111","stockNum":222,"unitPrice":333.0},
            {"id":1830,"specName":"321","stockNum":123,"unitPrice":123.0},
            {"id":1831,"specName":"sss","stockNum":34,"unitPrice":56.0}],
        "goods":{
            "id":476,
            "img":"http://115.29.141.32:8084/static/image/15712302279071567429968611lo.jpg",
            "name":"西服套装",
            "desc":"新品特卖asdfasdf",
            "typeId":1,
            "unitPrice":0.0
            }}}
         */

    /**
     * 获取某个商品ID对应的规格和goods信息等
     * @param request
     * @param response
     */
    private void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Map<String,Object> goodsInfo = goodsService.getGoodsInfo(id);
        response.getWriter().println(gson.toJson(Result.ok(goodsInfo)));
    }

    /**
     * 删除该商品条目
     * @param request
     * @param response
     */
    private void deleteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        int code = goodsService.deleteType(typeId);
        if (code == 200) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除失败")));
    }

    /**
     * 添加新的商品类型
     * @param request
     * @param response
     */
    private void addType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        //对请求报文进行处理
        AddTypeBO addTypeBO = gson.fromJson(requestBody,AddTypeBO.class);
        if (StringUtils.isEmpty(addTypeBO.getName())) {
            response.getWriter().println(gson.toJson(Result.error("输入的参数不能为空")));
            return;
        }
        int code = goodsService.addType(addTypeBO);
        if (code == 200) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("该种类已存在")));
    }

    /**
     * 根据商品类型的id来获取该类型下面的所有商品
     * 传来参数typeId
     * @param request
     * @param response
     */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        if (!StringUtils.isNumeric(typeId)) {
            response.getWriter().println(gson.toJson(Result.error("参数错误")));
            return;
        }
        List<Goods> goodsList = goodsService.getGoodsByType(typeId);
        response.getWriter().println(gson.toJson(Result.ok(goodsList)));
    }


}
